import network
import ujson
import 驱动.new_requests as urequests
import time
from setting import *
import _thread

def wifi_connect_thread():
    _thread.start_new_thread(connect_wifi, ())
    
def wifi_connect():
    print('wifi_connect..start.')
    wifi_times = 0
    
    wlan = network.WLAN(network.STA_IF)  # 创建STA模式
    
    print('网络连接中..1.')
    wlan.active(False)  # 激活wifi
    time.sleep(1)
    print('网络连接中..2.')
    wlan.active(True)  # 激活wifi
    time.sleep(1)
    print('网络连接中..3.')
    
    wlan.scan()
    print('网络连接中..4.')
    time.sleep(3)

    if not wlan.isconnected():  # 首次判断状态，尝试连接
        print('网络连接中...')
        while not wlan.isconnected():  # 用循环等待wifi连接（wifi连接需要点时间），每1s重新判断一次，若连接成功则不进入循环了
            wlan.active(True)
            wlan.connect(wifi_name, password)  # 连接wifi
            wifi_times += 1  # 计数器+1
            time.sleep(1)  # 每次等待1S
            print(wifi_times)
            if wifi_times == 20:  # 如果过了30S都没连上，判定连接失败
                wlan.active(False)
                return False  # 返回False

    print("wifi连接成功！")  # 若连接成功则不进入循环，从这里向下继续
    print('network connect', wlan.status())  # 返回网络工作状态,信号强度
    return True


def get_info():
    # {"fans": 0, "likes": 0, "coins": 0, "stars": 0, "now_stock": 0.0, "yes_stock": 0.0}
    r = urequests.get(f'http://api.bilibili.com/x/relation/stat?vmid={UID}')
    p = ujson.loads(r.text)
    fans = p['data']['follower']

    #r1 = urequests.get('https://api.bilibili.com/x/web-interface/archive/stat?bvid=' + bv_id)
    #p1 = ujson.loads(r1.text)
    #likes = p1['data']['like']
    #coins = p1['data']['coin']
    #stars = p1['data']['favorite']

    r2 = urequests.get('http://web.juhe.cn:8080/finance/stock/hs?gid=&type=0&key=9410eb82400dde354c6023a37eafd0e2')
    p2 = ujson.loads(r2.text)
    now_stock = round(float(p2['result']['nowpri']), 2)  # float将字符串转为浮点数，round四舍五入保留两位小数
    yes_stock = round(float(p2['result']['yesPri']), 2)

    print(f"粉丝为：{fans}")
    #print(f"点赞为：{likes}")
    #print(f"硬币为：{coins}")
    #print(f"收藏为: {stars}")
    print(f"上证指数为：{now_stock}")
    print(f"昨日上证指数为：{yes_stock}")

    #return {"fans": fans, "likes": likes, "coins": coins, "stars": stars, "now_stock": now_stock, "yes_stock": yes_stock}
    return {"fans": fans, "now_stock": now_stock, "yes_stock": yes_stock}



